<?php

/**
 * Name: 上传组件控制器
 * User: Silent
 * Date: 2025-10-09
 * Time: 20:53:13
 */

namespace App\Http\Controllers\V1\Resources\Components;

use App\Http\Controllers\Controller;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    const PHOTO_MAX_SIZE = 4194304;

    // 图片类型
    const ALLOW_FILE_EXTEND = ['jpg', 'png', 'jpeg'];

    /**
     * 上传图片操作.
     *
     * @param  Request  $request
     * @return array
     */
    public function upload(Request $request): array
    {
        $file     = $request->file('file');
        $location = $request->input('location', 'other');

        try {
            if ($request->hasFile('file') && $file->isValid()) {
                // 获取文件大小
                $fileSize = $file->getSize();
                // 获取文件全名称
                $fullName = $file->getClientOriginalName();
                // 获取文件名称
                $name = explode('.', $fullName);
                // 获取文件后缀
                $ext = $file->getClientOriginalExtension();
                // 获取上传类型
                $mimeType = 'image';

                if (!in_array($ext, self::ALLOW_FILE_EXTEND)) {
                    return $this->_error('图片格式不正确');
                }

                if ($fileSize > self::PHOTO_MAX_SIZE) {
                    return $this->_error('图片尺寸过大');
                }

                $dirPath  = config('filesystems.disks.oss.ossDir') . '/' . $location . '/' . date('Ym');
                $filePath = Storage::putFile($dirPath, $file);
                $path     = config('filesystems.disks.oss.cdnDomain') . '/' . $filePath;

                return $this->_success('上传成功', ['url' => $path]);
            }

            throw new Exception('参数错误');

        } catch (Exception $e) {
            Log::channel('upload')->error($e->getMessage());

            return $this->_error($e->getMessage());
        }
    }
}
